import React, { useState, useEffect } from "react"
import { Button, PageHeader, Table, Tag, Form, Input, DatePicker, Select } from "antd";
import { ArrowLeftOutlined, SearchOutlined, CloseOutlined } from "@ant-design/icons";
import moment from "moment";
import { useRequest } from '@umijs/hooks'
import { pageSetting, orderType } from "project-config"
import { formatResult } from "../../shared/libs/hooks/table-hooks"
import { get } from "server"
import { avatarPath } from "project-config"
import { clearner } from "../../shared/libs/utils"
import "./index.less";
import ClockCircleOutlined from "@ant-design/icons/lib/icons/ClockCircleOutlined";
import CrownOutlined from "@ant-design/icons/lib/icons/CrownOutlined";
import UserOutlined from "@ant-design/icons/lib/icons/UserOutlined";
import TeamOutlined from "@ant-design/icons/lib/icons/TeamOutlined";

const { RangePicker } = DatePicker;
const { Option } = Select;

const personObj = {
	// super_admin: <Tag className={'large'} color={'#d4380d'}><CrownOutlined/> 超级管理员</Tag>,
	// admin: <Tag className={'large'} color={'#d48806'}><UserOutlined /> 管理员</Tag>,
	// salesman: <Tag className={'large'} color={'#eb2f96'}><TeamOutlined /> 业务员</Tag>
	super_admin: "超级管理员",
	admin: "管理员",
	salesman: "业务员"
}

const LoginLogger = (props) => {
	const [adminList, setAdminList] = useState([]);
	const [form] = Form.useForm();

	useEffect(() => {
		get("/management/account/admin/findAccount").then(response => {
			if (response) setAdminList(response);
		})
	}, [])

	//获取数据
	const getPageData = ({
		current, pageSize, sorter, filters,
		// searchKey,
		roleType,
		accountId,
		beginTime,
		endTime,
	}) => {
		let type;
		if (filters && filters.type && filters.type.length === 1) {
			type = filters.type[0];
		}
		let sortKey;
		let sortType;
		if (sorter && sorter.columnKey && sorter.order) {
			sortKey = sorter.columnKey;
			sortType = orderType[sorter.order];
		}
		return get(`/management/logs/login/${pageSize}/${current}`, clearner({
			// searchKey,
			sortType,
			sortKey,
			roleType,
			type,
			accountId,
			beginTime,
			endTime,
		}))
	}


	const { tableProps, params, refresh, pagination } = useRequest(getPageData, {
		paginated: true,
		defaultPageSize: 10,
		formatResult,
	})

	const loggerColumns = [
		{
			title: "",
			dataIndex: "rowId",
			key: "rowId",
			render: (_, $, index) => <b>{index + 1}</b>
		}, {
			title: "帐号",
			dataIndex: "avatar",
			key: "avatar",
			render: (text, record) => (
				<div className="user-info">
					<div className="avatar">
						<img src={avatarPath(text)} />
					</div>
					<span>{record.loginName}</span>
				</div>
			)
		}, {
			title: '姓名',
			dataIndex: 'name',
			key: 'name',
		}, {
			title: '手机号码',
			dataIndex: 'phoneNo',
			key: 'phoneNo',
		}, {
			title: "IP",
			dataIndex: "ip",
			key: "ip"
		}, {
			title: '账号类型',
			dataIndex: 'role',
			key: 'role',
			render: text => personObj[text],
		}, {
			title: '类型',
			dataIndex: 'type',
			key: 'type',
			render: text => text === "login" ? <Tag color="#4CAF50" className="large">登录</Tag> : <Tag className="large" color="#f50">退出</Tag>,
			filters: [
				{ text: "登录", value: "login" },
				{ text: "退出", value: "logout" }
			],
		}, {
			title: '时间',
			key: 'createTime',
			dataIndex: 'createTime',
			sorter: true,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: (text) => text && <Tag className="large"><ClockCircleOutlined /> {text}</Tag>
		}
	]

	const onFinish = values => {
		const {
			durationDate,
			// searchKey,
			accountId,
			roleType
		} = values;
		let startDate, endDate;
		if (durationDate) {
			[startDate, endDate] = durationDate;
		}
		params[0] = {
			...params[0],
			// searchKey,
			accountId,
			beginTime: startDate && moment(startDate).valueOf(),
			endTime: endDate && moment(endDate).valueOf(),
			roleType,
		}
		refresh().finally()
	}

	const resetSearch = () => {
		form.resetFields();
		params[0] = {
			...params[0],
			// searchKey: '',
			accountId: '',
			beginTime: '',
			endTime: '',
			roleType: '',
		}
		refresh().finally()
	}


	const rangeConfig = {
		rules: [{ type: 'array', required: false, message: '' }],
	};

	return (
		<div className={'zr-panel'}>
			<div className={'zr-panel-header'}>
				<PageHeader backIcon={<ArrowLeftOutlined />} onBack={() => window.history.back()} title='登录日志' subTitle='' />
			</div>
			<div className={'zr-list-page-box body-bg body-border absolute'}>
				<Form
					form={form}
					name="basic"
					onFinish={onFinish}
					layout="inline"
					style={{
						margin: "20px 0px",
						justifyContent: "flex-end",
					}}
				>
					<Form.Item name="accountId" label="操作人员">
						<Select style={{ width: 200 }}
							showSearch
							allowClear
							filterOption={(input, option) =>
								option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
							}
						>
							{
								adminList.length > 0 && adminList.map(({ id, name, loginName }) => <Option key={id} value={id}>{`${name} | ${loginName}`}</Option>)
							}
						</Select>
					</Form.Item>
					<Form.Item name="roleType" label="角色类型">
						<Select allowClear
							style={{ width: 120 }}
						>
							{
								Object.keys(personObj).map(item => (
									<Option key={item} value={item}>{personObj[item]}</Option>
								))
							}
						</Select>
					</Form.Item>
					<Form.Item name="durationDate" label="日期段" {...rangeConfig}>
						<RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
					</Form.Item>
					<Form.Item>
						<Button type="primary" htmlType="submit" style={{ marginRight: 10 }}>
							<SearchOutlined /> 查询
						</Button>
						<Button onClick={resetSearch}><CloseOutlined /> 重置</Button>
					</Form.Item>
				</Form>
				<div className="zr-table-box">
					<Table
						{...tableProps}
						pagination={{
							...pagination,
							...pageSetting
						}}
						rowKey={record => record.id}
						size='middle'
						columns={loggerColumns} />
				</div>
			</div>
		</div>
	)
}

export default LoginLogger;